package cn.it.shop.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.it.shop.model.Audience;
import cn.it.shop.util.DateUtil;
import cn.it.shop.util.GlobalConstants;
import cn.it.shop.util.HttpPostUploadUtil;
import cn.it.shop.util.HttpUtils;
import cn.it.shop.util.JsonUtil;
import net.sf.json.JSONObject;

/***
 * 粉丝控制层
 * @author fangyangsheng
 *
 */
@Controller
@RequestMapping("/audience")
public class AudienceController extends BaseController{
	
	
	//变量
	private ServletContext application;
	
	/**
	 * 调用微信接口获取粉丝列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/index")
	public String goIndex(HttpServletRequest request){
		//System.out.println("audienceService: " + audienceService);
		//获取所有粉丝的openid
		List<Object> openIdList = audienceService.queryOpenidList();
		for(Object openId : openIdList){
			//根据openid查询所有用户详细信息
			Audience audience = audienceService.getAudience(openId.toString());
			//判断在数据库中是否已存在
			boolean isEmpty = audienceService.isEmptyAudience(audience.getOpenid());
			if(isEmpty){
				//保存进数据库
				audienceService.save(audience);
			}
		}
		//查询所有的粉丝
		List<Audience> audienceList = audienceService.query();
		//保存进application中
		application = request.getSession().getServletContext();
		application.setAttribute("audienceList", audienceList);
		return "redirect:/index2.jsp";
	}
	
	/***
	 * 查询粉丝详情
	 * @param audience
	 * @param request
	 * @return
	 */
	@RequestMapping("/getDetailed")
	public String getDetailed(Audience audience,HttpServletRequest request){
		List<Audience> audienceList = (List<Audience>)application.getAttribute("audienceList");
		for(Audience a : audienceList){
			if(a.getOpenid().equals(audience.getOpenid())){//如果openid一样
				//判断时间是否合法,需要不要转换
				if(!DateUtil.isDate(a.getSubscribe_time(), "yyyy-MM-dd HH:mm:ss")){
					//转换关注时间
					String date = DateUtil.timeStampDate(a.getSubscribe_time(), "yyyy-MM-dd HH:mm:ss");
					a.setSubscribe_time(date);
				}	
				request.getSession().setAttribute("audienceDetailed", a);
				return "redirect:/query.jsp";
			}
		}
		return "redirect:/query.jsp";
	}

	
	/**
	 * 跳转到发送信息页面
	 * @param audience
	 * @param request
	 * @return
	 */
	@RequestMapping("/toSendMessage")
	public String toSendMessage(Audience audience,HttpServletRequest request){
		request.getSession().setAttribute("openid", audience.getOpenid());
		return "redirect:/edit.jsp";
	}
	
	/**
	 * 发送信息,返回结果到浏览器(文本)
	 * @param audience
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/sendMessage")
	public String sendMessage(Audience audience,HttpServletRequest request,HttpServletResponse response){
		String text = request.getParameter("text");//获取文本消息
		//拼装 客服信息接口参数的json(文本)
		String jsonMessage = JsonUtil.messageJson(audience.getOpenid(), "text", text);
		//获取客服信息接口路径
		String sendMessage = GlobalConstants.getInterfaceUrl("sendMessage");
		//从全局变量工具类中取出access_token
		String accessToken = GlobalConstants.getInterfaceUrl("access_token");
		//拼装请求的url
		String urls = sendMessage+accessToken;
		/****
		 * 请求客服信息发送信息,需要粉丝先发送信息
		 * 
		 * 当用户和公众号产生特定动作的交互时（具体动作列表请见下方说明），
		 * 微信将会把消息数据推送给开发者，开发者可以在一段时间内（目前修改为48小时）调用客服接口
		 */
		String result = "";
		try {
			result = HttpUtils.sendPostBuffer(urls, jsonMessage);
			System.out.println("result:  " + result);
			// {"errcode":0,"errmsg":"ok"}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
		
	}
	
	
	/**
	 * 发送信息,返回结果到浏览器(图片)
	 * @param audience
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/sendImageMessage")
	public String sendImageMessage(Audience audience,HttpServletRequest request,HttpServletResponse response){
		String text = request.getParameter("text");//获取图片消息
		//获取图片的路径 jpg"
		text = text.substring(text.indexOf("src=\"")+5,text.indexOf(" title")-1);
		//获取ip地址+端口号
		String ipAddress = HttpUtils.getIpPort(request);
		//图片路径
		String imgPath = ipAddress + text;
		
		//构造方法里初始化请求路径
		//HttpPostUploadUtil  util = new HttpPostUploadUtil("image");
		HttpPostUploadUtil  util = new HttpPostUploadUtil("addMaterial","image");
        Map<String, String> textMap = new HashMap<String, String>();  
        textMap.put("name", "testname");  
        Map<String, String> fileMap = new HashMap<String, String>();  
        fileMap.put("userfile", imgPath); //上传临时素材 
     //   fileMap.put("media", imgPath); //上传永久素材
        String mediaidrs = util.formUpload(textMap, fileMap);//上传图片返回的json
        //取出media_id
        String mediaid = JSONObject.fromObject(mediaidrs).getString("media_id");
		
		//拼装 客服信息接口参数的json(图片)
		String jsonMessage = JsonUtil.imageJson(audience.getOpenid(), "image", mediaid);
		//获取客服信息接口路径
		String sendMessage = GlobalConstants.getInterfaceUrl("sendMessage");
		//从全局变量工具类中取出access_token
		String accessToken = GlobalConstants.getInterfaceUrl("access_token");
		//拼装请求的url
		String urls = sendMessage+accessToken;
		
		String result = "";
		try {
			result = HttpUtils.sendPostBuffer(urls, jsonMessage);
			//System.out.println("result:  " + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		return result;
		
	}
	
	
	
	public ServletContext getApplication() {
		return application;
	}

	public void setApplication(ServletContext application) {
		this.application = application;
	}	
	
	
	
}
